#include "./../../inc/page_manager.h"
#include "./../../inc/homepage.h"

lv_obj_t * page_history[MAX_HISTORY];
int history_index = -1;

// 初始化页面历史
void init_page_history(void)
{
    for(int i = 0; i < MAX_HISTORY; i++) {
        page_history[i] = NULL;
    }
    history_index = -1;
}

// 跳转到新页面
void navigate_to(lv_obj_t * new_page)
{
    // 如果历史栈已满，移除最旧的页面
    if(history_index >= MAX_HISTORY - 1) {
        for(int i = 0; i < MAX_HISTORY - 1; i++) {
            page_history[i] = page_history[i + 1];
        }
        history_index = MAX_HISTORY - 2;
    }

    // 隐藏当前页面
    if(history_index >= 0) {
        lv_obj_add_flag(page_history[history_index], LV_OBJ_FLAG_HIDDEN);
    }

    // 添加新页面到历史
    history_index++;
    page_history[history_index] = new_page;

    // 显示新页面
    lv_scr_load(new_page);
}

// 返回上一个页面
void back(lv_event_t * e)
{
    if(history_index > 0) {
        // 隐藏当前页面
        lv_obj_add_flag(page_history[history_index], LV_OBJ_FLAG_HIDDEN);

        // 显示上一个页面
        history_index--;
        lv_obj_clear_flag(page_history[history_index], LV_OBJ_FLAG_HIDDEN);
        lv_scr_load(page_history[history_index]);
    }
}

// 返回到主页
void back_to_home(lv_event_t * e)
{
    if(history_index > 0 && page_history[0] != NULL) {
        // 隐藏当前页面
        lv_obj_add_flag(page_history[history_index], LV_OBJ_FLAG_HIDDEN);

                // 显示主页
        history_index = 0;
        lv_obj_clear_flag(page_history[0], LV_OBJ_FLAG_HIDDEN);
        lv_scr_load(page_history[0]);
    }
}